import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:test1/View/MyRowText.dart';

class Flutter_Net_Dio_Page extends StatelessWidget with RequestCallBack {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("dio"),
        ),
        body: Container(
            color: Color(0xfff1f1f1),
            child: ListView(
              children: <Widget>[
                MyRowText(
                    "post",
                    () => doRequest(
                        "http://www.wanandroid.com/user/login",
                        {
                          "username": "hellonews",
                          "password": 123456,
                        },
                        this)),
                MyRowText(
                    "get",
                    () => doRequest2(
                        "http://api.douban.com/v2/movie/top250?start=0&count=5",
                        this)),
              ],
            )),
      ),
    );
  }

  /**
   * 1.需要集成dio，在pubspec.yaml文件中添加dio
   * 2.导入dio包
   */

  void doRequest(String url, Map<String, dynamic> params,
      RequestCallBack requestCallBack) async {
    FormData formData = new FormData.fromMap(params);

//    Options options= new Options(
    // 15s 超时时间
//        connectTimeout:15000,
//        receiveTimeout:15000,
//        baseUrl: "",
    // dio库中默认将请求数据序列化为json，此处可根据后台情况自行修改
//        contentType:  ContentType('application', 'x-www-form-urlencoded',charset: 'utf-8')
//    );
    Dio dio = new Dio();
    Response response = await dio.post(url, data: formData);
    if (response.statusCode == 200) {
      requestCallBack.onSuccess(response.toString());
    } else {
      requestCallBack.onError();
    }
  }

  void doRequest2(String url, RequestCallBack requestCallBack) async {
    BaseOptions options = new BaseOptions(
        // 15s 超时时间
        connectTimeout: 15000,
        sendTimeout: 15000,
        receiveTimeout: 15000,
        baseUrl: ""
        // dio库中默认将请求数据序列化为json，此处可根据后台情况自行修改
//        contentType:  ContentType('application', 'x-www-form-urlencoded',charset: 'utf-8')
        );
    Dio dio = new Dio(options);
    Response response = await dio.get(url);
    if (response.statusCode == 200) {
      requestCallBack.onSuccess(response.toString());
    } else {
      requestCallBack.onError();
    }
  }

  @override
  void onError() {}

  @override
  void onSuccess(String result) {
    print(result);
  }
}

abstract class RequestCallBack {
  void onSuccess(String result);

  void onError();
}
